<template>
  <div class="account">
    <el-form
      :model="account"
      :rules="accountRules"
      label-width="60px"
      status-icon
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" maxlength="15" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="account.password"
          maxlength="16"
          show-password
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { type FormRules, type ElForm, ElMessage } from 'element-plus'
import { useLoginStore } from '@/stores/login/login'
import type { ILoginAccount } from '@/types/index'
import { localCache } from '@/utils/cache'
import { ACCOUNTNAME, ACCOUNTPASSWORD } from '@/types/constant'

// 定义数据
const account = reactive<ILoginAccount>({
  name: localCache.getCache(ACCOUNTNAME) ?? '',
  password: localCache.getCache(ACCOUNTPASSWORD) ?? ''
})

// 校验数据
const accountRules = reactive<FormRules>({
  name: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,16}$/,
      message: '密码由6到11位的数字或字母组成',
      trigger: 'change'
    }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,11}$/,
      message: '密码由6到11位的数字或字母组成',
      trigger: 'change'
    }
  ]
})

// 调用子组件方法
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
function loginAction(hasRemPwd: Boolean) {
  // 校验输入数据
  formRef.value?.validate((valid) => {
    if (valid) {
      // console.log('校验成功')
      // 获取数据
      const name = account.name
      const password = account.password

      loginStore.fetchLoginAccountAction({ name, password }).then(() => {
        // 判断是否记住密码
        if (hasRemPwd) {
          localCache.setCache(ACCOUNTNAME, name)
          localCache.setCache(ACCOUNTPASSWORD, password)
        } else {
          localCache.removeCache(ACCOUNTNAME)
          localCache.removeCache(ACCOUNTPASSWORD)
        }
      })
    } else {
      console.log('校验失败哦')
      ElMessage.error('Oops, this is a error message.')
    }
  })
}

defineExpose({ loginAction })
</script>

<style lang="scss" scoped></style>
